package com.cloud.lan.api.manage;

import com.cloud.lan.api.dto.req.LanManageUserReq;
import com.cloud.lan.api.dto.req.LanUserReq;
import com.cloud.lan.api.dto.req.WxDataReq;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.service.ILanManageUserService;
import com.cloud.lan.service.ILanUserService;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

/**
 * 用户信息入口
 * @author ErKang
 * @date Created in 2021/12/5 04:24
 * @title TestApi.java
 * Department: Product development
 */
@RestController
@RequestMapping(value = {"/v1/manage/user/"}, method = {RequestMethod.GET, RequestMethod.POST}, produces = {"application/json"})
public class LanUserManageApi {

    @Resource
    ILanManageUserService lanManageUserService;
    @Resource
    ILanUserService lanUserService;

    @RequestMapping("login")
    public BaseResponse<Object> login(@RequestBody LanManageUserReq request) {
        return lanManageUserService.login(request);
    }

    @RequestMapping("manageList")
    public BaseResponse<Object> manageList(LanUserReq request) {
        return lanManageUserService.manageList(request);
    }

    @RequestMapping("/exportUser")
    public void exportUser(HttpServletResponse response, String beginDate, String endDate) throws IOException {
        List<LinkedHashMap<String, Object>> rows = lanManageUserService.exportUser(beginDate, endDate);
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter();
        //自定义标题别名
        //writer.addHeaderAlias("nick_name", "昵称");
        writer.write(rows, true);
        response.setContentType("application/octet-stream;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=exportUser-" + RandomUtil.randomString(5) + ".xls");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

    @RequestMapping("getWxData")
    public BaseResponse<Object> getWxData(@RequestBody WxDataReq req) {
        return lanUserService.getWxData(req);
    }
}
